package dao;

import model.Book;
import model.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {






    public List<Book> selectAll(Connection con) throws SQLException {


        List<Book> userlist=new ArrayList<Book>();

        String sql ="select * from Book";

        PreparedStatement preparedStatement =(PreparedStatement) con.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();


        while(resultSet.next()){{
            Book book=new Book();
            book.setBookId(resultSet.getInt("id"));
            book.setBookName(resultSet.getString("book_name"));
            book.setBookTypeId(resultSet.getInt("type_id"));
            book.setAuthor(resultSet.getString("author"));
            book.setRemark(resultSet.getString("remark"));

            userlist.add(book);

        }}



        return userlist;

    }



    public List<Book> selectByBook(Connection con, Book book) throws SQLException {


        List<Book> bookList = new ArrayList<>();


        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM Book WHERE ");




        List<Object> params = new ArrayList<>();




        if (book.getAuthor() != null) {
            sqlBuilder.append("author=?");
            params.add(book.getAuthor());


        } else if (book.getBookName() != null) {
            sqlBuilder.append("book_name=?");
            params.add(book.getBookName());


        }

        PreparedStatement preparedStatement = con.prepareStatement(sqlBuilder.toString());



        // 设置参数
        for (int i = 0; i < params.size(); i++) {
            preparedStatement.setObject(i + 1, params.get(i));
        }



        ResultSet rs = preparedStatement.executeQuery();

        while (rs.next()) {
            Book resultBook = new Book();
            resultBook.setBookId(rs.getInt("id"));
            resultBook.setBookName(rs.getString("book_name"));
            resultBook.setBookTypeId(rs.getInt("type_id"));
            resultBook.setAuthor(rs.getString("author"));
            resultBook.setRemark(rs.getString("remark"));
            bookList.add(resultBook);
        }



        return bookList;




    }




}
